package weaver.interfaces.ybcn.duss.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author dusongsong
 * @date 2024年03月18日 09:46
 */
public class T100Util extends BaseBean {

    //请求地址-测试区
    private static final String URL = "http://10.6.19.71/wtoptst/ws/r/awsp920";

    /**
     * 员工报销申请单生成接口
     *
     * @param dataJson
     * @return
     */
    public JSONObject apDataCreateOa(JSONObject dataJson,String jkdymc,String requestid,String src) {
        String key ="1fece0cb254f1f45891bc9ee9fed72a9";
        String serviceName ="ap.data.create_oa";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("jkdymc", jkdymc);
        dataMap.put("lcid", requestid);
        dataMap.put("cz", src);
        return commonParamHandle(dataJson, serviceName,key,dataMap);
    }

    /**
     * 采购核价单生成接口
     *
     * @param dataJson
     * @return
     */
    public JSONObject PriceListCreate(JSONObject dataJson,String jkdymc,String requestid,String src) {
        String key ="f5458f5c0f9022db743a7c0710145903";
        String serviceName ="PriceListCreate";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("jkdymc", jkdymc);
        dataMap.put("lcid", requestid);
        dataMap.put("cz", src);
        return commonParamHandle(dataJson, serviceName,key,dataMap);
    }
    /**
     * cwssp018采购单生成接口
     *
     * @param dataJson
     * @return
     */
    public JSONObject CPurchaseOrderCreate(JSONObject dataJson,String jkdymc,String requestid,String src) {
        String key ="1fece0cb254f1f45891bc9ee9fed72a9";
        String serviceName ="CPurchaseOrderCreate";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("jkdymc", jkdymc);
        dataMap.put("lcid", requestid);
        dataMap.put("cz", src);
        return commonParamHandle(dataJson, serviceName,key,dataMap);
    }

    /**
     * cwssp041供应商生成修改接口
     *
     * @param dataJson
     * @return
     */
    public JSONObject ClentSupplierCreat(JSONObject dataJson,String jkdymc,String requestid,String src) {
        String key ="1fece0cb254f1f45891bc9ee9fed72a9";
        String serviceName ="ClentSupplierCreat";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("jkdymc", jkdymc);
        dataMap.put("lcid", requestid);
        dataMap.put("cz", src);
        return commonParamHandle(dataJson, serviceName,key,dataMap);
    }

    /**
     * cwssp009新增修改料件基础资料接口
     *
     * @param dataJson
     * @return
     */
    public JSONObject ItemCreate(JSONObject dataJson,String jkdymc,String requestid,String src) {
        String key ="f5458f5c0f9022db743a7c0710145903";
        String serviceName ="ItemCreate";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("jkdymc", jkdymc);
        dataMap.put("lcid", requestid);
        dataMap.put("cz", src);
        return commonParamHandle(dataJson, serviceName,key,dataMap);
    }
    /**
     * cwssp042新增修改客户资料接口
     *
     * @param dataJson
     * @return
     */
    public JSONObject ClentCreat(JSONObject dataJson,String jkdymc,String requestid,String src) {
        String key ="1fece0cb254f1f45891bc9ee9fed72a9";
        String serviceName ="ClentCreat";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("jkdymc", jkdymc);
        dataMap.put("lcid", requestid);
        dataMap.put("cz", src);
        return commonParamHandle(dataJson, serviceName,key,dataMap);
    }
    /**
     * cwssp012生成销售合同单接口
     *
     * @param dataJson
     * @return
     */
    public JSONObject CreateSalesContract(JSONObject dataJson,String jkdymc,String requestid,String src) {
        String key ="f5458f5c0f9022db743a7c0710145903";
        String serviceName ="CreateSalesContract";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("jkdymc", jkdymc);
        dataMap.put("lcid", requestid);
        dataMap.put("cz", src);
        return commonParamHandle(dataJson, serviceName,key,dataMap);
    }
    /**
     * cwssp013生成销售合同变更单接口
     *
     * @param dataJson
     * @return
     */
    public JSONObject ContractChangesCreate(JSONObject dataJson,String jkdymc,String requestid,String src) {
        String key ="f5458f5c0f9022db743a7c0710145903";
        String serviceName ="ContractChangesCreate";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("jkdymc", jkdymc);
        dataMap.put("lcid", requestid);
        dataMap.put("cz", src);
        return commonParamHandle(dataJson, serviceName,key,dataMap);
    }
    /**
     * 15.	cwssp103生成项目立项接口
     *
     * @param dataJson
     * @return
     */
    public JSONObject ProjectApprovalCreate(JSONObject dataJson,String jkdymc,String requestid,String src) {
        String key ="f5458f5c0f9022db743a7c0710145903";
        String serviceName ="ProjectApprovalCreate";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("jkdymc", jkdymc);
        dataMap.put("lcid", requestid);
        dataMap.put("cz", src);
        return commonParamHandle(dataJson, serviceName,key,dataMap);
    }



    /**
     * 通用参数处理
     *
     * @param dataJson
     * @param serviceName
     * @return
     */

    private JSONObject commonParamHandle(JSONObject dataJson, String serviceName,String key,Map<String, Object> dataMap) {
        JSONObject paramsJson = new JSONObject();
        //唯一值
        paramsJson.put("key", key);
        //类型
        paramsJson.put("type", "sync");
        JSONObject hostJson = new JSONObject();
        //客户端产品
        hostJson.put("prod", "APP");
        //客户端ip
        hostJson.put("ip", "10.6.20.24");
        //客户端语言
        hostJson.put("lang", "zh_CN");
        //用户
        hostJson.put("acct", "tiptop");
        //时间戳
        hostJson.put("timestamp", getTimestamp());
        paramsJson.put("host", hostJson);
        JSONObject serviceJson = new JSONObject();
        //服务端
        serviceJson.put("prod", "T100");
        //服务名
        serviceJson.put("name", serviceName);
        //服务端ip
        serviceJson.put("ip", "172.16.11.152");
        //产品
        serviceJson.put("id", "topprd");
        paramsJson.put("service", serviceJson);
        JSONObject datakeyJson = new JSONObject();
        //企业代码
        datakeyJson.put("EntId", "6");
        //营运据点
        datakeyJson.put("CompanyId", Util.null2String(dataMap.get("gc")));
        paramsJson.put("datakey", datakeyJson);
        paramsJson.put("payload", dataJson);
        JSONObject resultJson = sendOKHttpRequest(paramsJson.toJSONString());
        dataMap.put("jkqqcs", paramsJson);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap);
        return resultJson;
    }

    /**
     * 发起请求
     *
     * @param paramJson
     * @return
     */
    private JSONObject sendOKHttpRequest(String paramJson) {
        JSONObject resultJson = new JSONObject();
        String data = "";
        String message = "";
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, paramJson);
            Request request = new Request.Builder()
                    .url(URL)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                data = result;
                message = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }


    /**
     * 获取当前时间戳
     * @return
     */
    public  String getTimestamp() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(new Date());
    }
    /**
     * 获取日期格式转时间戳
     * @return
     */
    public  String getTimestamp(String rq) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(DateUtil.parseToDate(rq));
    }

    /**
     * 插入接口日志
     *
     * @param dataMap
     */
    private  void insertApiLog(Map<String, Object> dataMap) {
        dataMap.put("jkqqdz", URL);
        dataMap.put("jkdysj", DateUtil.getFullDate());
        dataMap.put("jktgf", "T100");
        insertModelData("uf_apilog", 1, dataMap);
    }

    /**
     * 建模权限重构
     * @param userid
     * @param formmodeid
     * @param id
     */
    private  void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    /**
     * 将数据插入表单建模
     * @param tablename
     * @param userid
     * @param map
     * @return
     */
    private int insertModelData(String tablename, int userid, Map<String, Object> map) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        try {
            String sql = "select a.id from modeinfo a left join workflow_bill b on a.formid=b.id where b.tablename=?";
            rs.execute(sql, tablename);
            rs.next();
            int modeid = Util.getIntValue(rs.getString("id"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values" +
                    "('"+uuid+"','"+userid+"','"+TimeUtil.getCurrentDateString()+"','"+TimeUtil.getOnlyCurrentTimeString()+"','"+modeid+"')";
            if (rs.execute(insSql)) {
                rs1.execute("select id from " + tablename + " where modeuuid=?", uuid);
                rs1.next();
                dataid = Util.getIntValue(rs1.getString("id"));
                if (dataid > 0) {
                    //遍历数据 进行update
                    String updatesql = "update " + tablename + " set ";
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        if("jkqqcs".equals(key) && Util.null2String(map.get(key)).length()>4000){
                            updatesql += key + "='" + map.get(key).toString().substring(0,4000) + "',";
                        }else {
                            updatesql += key + "='" + map.get(key).toString() + "',";
                        }
                    }
                    if (updatesql.endsWith(",")) {
                        updatesql = updatesql.substring(0, updatesql.length() - 1);
                        updatesql += " where id=" + dataid;
                        rs.execute(updatesql);
                    }
                    //进行权限重构
                    newModeRight(userid, modeid, dataid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataid;
    }

    /**
     * 根据userid获取用户信息
     * @param userid
     * @return
     */
    public  Map<String,Object> getUserInfoByid(String userid) {
        Map<String,Object> userInfoMap = new HashMap<>();
        RecordSet rs = new RecordSet();
        rs.execute("select n.loginid,n.workcode,n.departmentid,m.departmentcode from hrmresource n join hrmdepartment m on n.departmentid=m.id where n.id=?",userid);
        rs.next();
        userInfoMap.put("loginid",Util.null2String(rs.getString("loginid")));
        userInfoMap.put("workcode",Util.null2String(rs.getString("workcode")));
        userInfoMap.put("departmentid",Util.null2String(rs.getString("departmentid")));
        userInfoMap.put("departmentcode",Util.null2String(rs.getString("departmentcode")));
        return userInfoMap;
    }

}
